﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SalePartial.Utility;
using System.Web.UI;
using System.Web;
using System.Web.Security;
using System.Data;
using System.Data.SqlClient;

namespace SalePartial.BLL
{
    public class RoleControlManager
    {
        public static LoginUserType checkUserAuthority(string userNm)
        {
            if (userNm == null || userNm == string.Empty)
            {
                return LoginUserType.GUEST;
            }

            if (HttpContext.Current.Session[ConstantSession.LOGIN_USER_AUTH_TYPE] != null)
            {
                return (LoginUserType)HttpContext.Current.Session[ConstantSession.LOGIN_USER_AUTH_TYPE];
            }
 
           MembershipUserCollection userList =  Membership.FindUsersByEmail(userNm);
            if(userList == null)
            {
                return LoginUserType.GUEST;
            }
           //string[] roles = Roles.GetRolesForUser(userNm);
           //if (roles == null || roles.Length == 0)
           //{
           //    return LoginUserType.GUEST;
           //}
           
           if (Roles.IsUserInRole(userNm, "Administrators"))
           {
               return LoginUserType.ADMIN;
           }

           XPCompany company = new XPCompany();
           string v_whereCondition = "UserID='" + userList[userNm].ProviderUserKey+"'";
            string v_orderByExpression = "";
            DataSet ds = company.SelectDynamic(v_whereCondition, v_orderByExpression);
           if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
           {
               return LoginUserType.PERSONAL;
           }

           LoginUserType type = new LoginUserType();
           foreach(DataRow dr in ds.Tables[0].Rows)
           {
               if (dr["BuyerModerateStatus"].ToString() == "2")
               {
                   type = type == LoginUserType.GUEST ? LoginUserType.CERT_PURCHASE : LoginUserType.CERT_SUP_PUR;
               }
               else if (dr["BuyerModerateStatus"].ToString() == "1")
               {
                   type = type == LoginUserType.GUEST ? LoginUserType.FREE_PURCHASE : LoginUserType.FREE_SUP_PUR;
               }
               if (dr["VendorModerateStatus"].ToString() == "2")
               {
                   type = type == LoginUserType.GUEST ? LoginUserType.CERT_SUPPLY : LoginUserType.CERT_SUP_PUR;
               }
               else if (dr["VendorModerateStatus"].ToString() == "1")
               {
                   type = type == LoginUserType.GUEST ? LoginUserType.FREE_SUPPLY : LoginUserType.FREE_SUP_PUR;
               }
             
           }

           if (type == LoginUserType.GUEST && Roles.IsUserInRole(userNm, "Individual"))
           {
               return LoginUserType.PERSONAL;
           }

           return type;

        }


        public static bool checkAceessValidity(string userNm, string appId)
        {
            if (userNm == null || userNm == string.Empty ||
                appId == null || appId == string.Empty)
            {
                return false;
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("  select count(*) AS cnt");
            sb.Append("  from Func_Power");
            sb.Append("  where Role_mg_id in");
            sb.Append("  (select Role_mg_id from aspnet_UsersInRoles UR,");
            sb.Append("  	aspnet_Membership M");
            sb.Append("  	where M.UserId = UR.UserId and M.Email = @Email)");
            sb.Append("  and fi_no2 =(select fi_no2 from Func_Item2 where fi_url2=@fi_url2);");

            string cnt = "0";
            try
            {
                using (SqlConnection Sql_Conn = new SqlConnection(GlobalSetting.ConnectionString))
                {

                    using (SqlCommand Sql_Command = new SqlCommand())
                    {
                        Sql_Conn.Open();

                        SqlDataReader Sql_Reader = null;
                        Sql_Command.Connection = Sql_Conn;
                        Sql_Command.CommandText = sb.ToString();
                        Sql_Command.Parameters.AddWithValue("@Email", userNm);
                        Sql_Command.Parameters.AddWithValue("@fi_url2", appId);
                        Sql_Reader = Sql_Command.ExecuteReader();
                        if (Sql_Reader.Read())
                        {
                            cnt = Sql_Reader["cnt"].ToString().Trim();

                            Sql_Command.Dispose();
                            Sql_Reader.Close();
                        }
                    }
                    Sql_Conn.Dispose();
                    Sql_Conn.Close();
                    Sql_Conn.Dispose();
                }
            }
            catch (Exception)
            {

            }

            if (Convert.ToInt32(cnt) <= 0)
            {
                return false;
            }

            return true;
        }

        public static void LoginOut()
        {
            FormsAuthentication.SignOut();
            Roles.DeleteCookie();
            HttpContext.Current.Session.Clear();
            HttpContext.Current.Session.Abandon();
        }
    }
}
